<template>
  <div>
    <!-- 查询区域 -->
    <el-form :inline="true" label-width="auto" style="margin-bottom: 20px;">
      <el-form-item label="病历号或姓名">
        <el-input
            v-model="keywords"
            placeholder="请输入病历号或姓名"
            style="width: 260px"
            clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchTests">
          <el-icon>
            <Search/>
          </el-icon>
          查询
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 患者信息展示 -->
    <el-form :inline="true" label-width="auto" style="margin-bottom: 20px;">
      <el-form-item label="姓名">
        <el-input v-model="patientInfo.realName" readonly style="width: 180px"/>
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input v-model="patientInfo.idNumber" readonly style="width: 250px"/>
      </el-form-item>
      <el-form-item label="家庭住址">
        <el-input v-model="patientInfo.address" readonly style="width: 400px"/>
      </el-form-item>
    </el-form>

    <!-- 检验申请列表 -->
    <el-table
        :data="testList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        :row-key="row => row.Id"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column label="病历号" prop="MedicalID" width="120"/>
      <el-table-column label="项目名称" prop="ItemName" width="200"/>
      <el-table-column label="数量" prop="Num" width="80"/>
      <el-table-column label="开立时间" prop="CreationTime" width="180"/>
      <el-table-column label="状态" prop="State" width="120">
        <template #default="{ row }">
          <span v-if="row.State === 1">已开立未缴费</span>
          <span v-else-if="row.State === 2">已收费</span>
          <span v-else-if="row.State === 3">已执行</span>
          <span v-else-if="row.State === 0">结果已录入</span>

          <span v-else>未知</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 操作按钮 -->
    <div style="margin-top: 15px;">
      <el-button
          type="primary"
          :disabled="selectedTests.length === 0"
          @click="confirmExecution"
          style="margin-right: 10px"
      >
        执行确认
      </el-button>
      <el-button
          type="warning"
          :disabled="selectedTests.length === 0"
          @click="cancelExecution"
          style="margin-right: 10px"
      >
        取消执行
      </el-button>
      <el-button
          type="success"
          :disabled="selectedTests.length === 0"
          @click="openResultDialog"
      >
        结果录入
      </el-button>
    </div>

    <!-- 结果录入弹窗 -->
    <el-dialog
        title="结果录入"
        v-model="resultDialogVisible"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-input
          type="textarea"
          rows="6"
          v-model="resultText"
          placeholder="请输入检验结果..."
      />
      <template #footer>
        <el-button @click="resultDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitResult">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import service from '@/utils/request'
import {ElMessage} from 'element-plus'
import {Search} from '@element-plus/icons-vue'

// 搜索关键字
const keywords = ref('')

// 患者信息
const patientInfo = ref({realName: '', idNumber: '', address: ''})

// 检验项目列表
const testList = ref([])

// 多选框选中的项目
const selectedTests = ref([])

// 加载中状态
const loading = ref(false)

// 结果录入弹窗控制
const resultDialogVisible = ref(false)
const resultText = ref('')
const resultTargetId = ref(null)

// 查询检验申请
function searchTests() {
  if (!keywords.value) {
    ElMessage.warning('请输入病历号或姓名进行查询')
    return
  }

  loading.value = true
  service
      .get('/check/getbymid?mid=' + keywords.value)
      .then(res => {
        loading.value = false
        if (res.data && res.data.list && res.data.list.length > 0) {
          testList.value = res.data.list
          const info = res.data.info || res.data.list[0]
          patientInfo.value.realName = info.realname || info.RealName || ''
          patientInfo.value.idNumber = info.idnumber || info.IDnumber || ''
          patientInfo.value.address = info.homeaddress || info.HomeAddress || ''
        } else {
          ElMessage.info('未找到相关检验申请')
          testList.value = []
          patientInfo.value = {realName: '', idNumber: '', address: ''}
        }
      })
      .catch(() => {
        loading.value = false
        ElMessage.error('查询失败，请稍后重试')
      })
}

// 多选监听
function handleSelectionChange(val) {
  selectedTests.value = val
}

// 执行确认
function confirmExecution() {
  if (selectedTests.value.some(item => item.State !== 2)) {
    ElMessage.warning('只有【已收费】状态的项目才能执行确认')
    return
  }

  const ids = selectedTests.value.map(item => item.Id)
  service.post('/check/execute', {ids})
      .then(() => {
        ElMessage.success('执行确认成功')
        searchTests()
      })
      .catch(() => {
        ElMessage.error('执行确认失败')
      })
}

// 取消执行
function cancelExecution() {
  if (selectedTests.value.some(item => item.State !== 3)) {
    ElMessage.warning('只有【已执行】状态的项目才能取消执行')
    return
  }

  const ids = selectedTests.value.map(item => item.Id)
  service.post('/check/cancelExecute', {ids})
      .then(() => {
        ElMessage.success('取消执行成功')
        searchTests()
      })
      .catch(() => {
        ElMessage.error('取消执行失败')
      })
}

// 打开录入弹窗
function openResultDialog() {
  if (selectedTests.value.length !== 1) {
    ElMessage.warning('请仅选择一个项目进行录入')
    return
  }

  const selected = selectedTests.value[0]
  if (selected.State !== 3) {
    ElMessage.warning('只有【已执行】状态的项目才能录入结果')
    return
  }

  resultTargetId.value = selected.Id
  resultText.value = selected.Result || ''
  resultDialogVisible.value = true
}

// 提交结果
function submitResult() {
  if (!resultText.value.trim()) {
    ElMessage.warning('请输入检验结果内容')
    return
  }
  const params = new URLSearchParams()
  params.append('id', resultTargetId.value)
  params.append('result', resultText.value.trim())
  params.append('resultOperID', 1)  // 替换成真实ID

  service.post('/check/inputResult', params)
      .then(res => {
        if (res.data.code === 200) {
          ElMessage.success('结果录入成功')
          resultDialogVisible.value = false
          searchTests()
        } else {
          ElMessage.error('录入失败：' + (res.data.message || '未知错误'))
        }
      })
      .catch(() => {
        ElMessage.error('提交失败，请稍后重试')
      })
}
</script>

